﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormMachineTimeSheet : FormBaseDataGrid
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsTimeSheet;
        private SqlDataAdapter mdaTimeSheetUpdate;

        public FormMachineTimeSheet()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        #region Override LoadMasterData
        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
                btnImport.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Machine Time Sheet Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        #endregion

        #region LoadData method
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                cboYear.Text = DateTime.Now.Year.ToString();
                cboMonth.Text = (DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString());

                string lCondiction = " Where TS.Years = " + cboYear.Text.Trim() + " and TS.Months = " + cboMonth.Text.Trim() + " Order By TS.ID_Emp ";
                string lCondiction1 = " Years = " + cboYear.Text.Trim() + " and Months = " + cboMonth.Text.Trim() + " Order By ID_Emp ";

                string ls_SQL = "Select TS.ID_Emp, PF.Emp_NameVN, TS.Years, TS.Months, TS.Wrk_Date, TS.DayOfWeek, TS.ID_Shift, DS.Shift_Name, DS.Begin_Hrs, DS.End_Hrs,  "
                    + " TS.Time_In, TS.Time_Out, TS.Note, TS.CreatedUser, TS.UpdatedUser, TS.CreatedDate, TS.UpdatedDate "
                    + "From HRM_PersonnelMachineTimeSheet TS inner join HRM_PersonalProfile PF on TS.ID_Emp = PF.ID_Emp "
                    + " inner join HRM_DefineShift DS on TS.ID_Shift = DS.ID_Shift "
                    + lCondiction;

                mdsTimeSheet = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelMachineTimeSheet");
                mCtrlGeneral.GetDataWithCondition(out mdaTimeSheetUpdate, "HRM_PersonnelMachineTimeSheet", lCondiction1);

                if (mdsTimeSheet == null) return;
                mdbg_dataGrid.DataSource = mdsTimeSheet;
                mdbg_dataGrid.DataMember = "HRM_PersonnelMachineTimeSheet";


                mRowManager = (CurrencyManager)mdbg_dataGrid.BindingContext[mdsTimeSheet, "HRM_PersonnelMachineTimeSheet"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Machine Time Sheet Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Machine Time Sheet Form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        public override void save()
        {
            try
            {
                if (mdsTimeSheet == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsTimeSheet.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsTimeSheet.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["DayOfWeek"] = DateTime.Parse(dr["Wrk_Date"].ToString()).DayOfWeek;
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["Years"] = cboYear.Text.Trim();
                        dr["Months"] = cboMonth.Text;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["DayOfWeek"] = DateTime.Parse(dr["Wrk_Date"].ToString()).DayOfWeek;
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaTimeSheetUpdate, ldsHasChanged, "HRM_PersonnelTimeSheetDtl", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsTimeSheet.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    btnBrowse.Enabled = true;
                    btnImport.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Cannot save Machine Time Sheet data'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void cancel()
        {
            mdbg_dataGrid.Focus();
            if (mdsTimeSheet == null) return;
            mRowManager.EndCurrentEdit();
            mdsTimeSheet.RejectChanges();
            base.cancel();
            btnBrowse.Enabled = true;
            btnImport.Enabled = false;
        }

        public override void add()
        {
            mdbg_dataGrid.Focus();
            base.add();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }

        public override void modify()
        {
            base.modify();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }

        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaTimeSheetUpdate, ldsDelete, "HRM_PersonnelMachineTimeSheet", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete Machine Time Sheet data'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {   //string lsPathFileName;
                DataSet ldsImport = new DataSet();
                OpenFileDialog openFileDialog = new OpenFileDialog();
                //openFileDialog.InitialDirectory = Application.StartupPath;
                openFileDialog.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
                openFileDialog.FilterIndex = 0;
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // Add Code here:
                    lblFilePath.Text = openFileDialog.FileName;
                    btnImport.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot import Machine Time Sheet data. Error: '" + ex.Message + "'", ConstantKeys.Title);
            }
        }

        #region CellValueChanged Event
        private void mdbg_dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            string ls_SQL = String.Empty;
            string ls_IDEmp = mdbg_dataGrid["ID_Emp", e.RowIndex].Value.ToString();
            string lsWrkDate = mdbg_dataGrid["Wrk_Date", e.RowIndex].Value.ToString();
            if (lsWrkDate.Equals(""))
                lsWrkDate = DateTime.Now.ToString("yyyy/MM/dd");
            else
               lsWrkDate = DateTime.Parse(mdbg_dataGrid["Wrk_Date", e.RowIndex].Value.ToString()).ToString("yyyy/MM/dd");

            DataSet lds;

            if (e.ColumnIndex == 0)
            {
                lds = mCtrlGeneral.GetSelect(" Select Emp_NameVN, FollowTimeAtt From HRM_PersonalProfile Where ID_Emp = '" + ls_IDEmp + "'", "HRM_PersonalProfile");
                mdbg_dataGrid["Emp_NameVN", e.RowIndex].Value = lds.Tables[0].Rows[0]["Emp_NameVN"];
                ////
                ls_SQL = "select PS.ID_Shift, DS.Shift_Name, DS.Begin_Hrs, DS.End_Hrs "
                        + " From dbo.HRM_PersonnelShift PS inner join dbo.HRM_DefineShift DS on PS.ID_Shift = DS.ID_Shift "
                        + " where PS.ID_Emp = '" + ls_IDEmp + "' "
                        + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) "
                        + " and Convert(varchar(8), PS.End_Date, 112) >=Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) ";
                lds = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelShift");
                if (lds.Tables[0].Rows.Count > 0)
                {
                    mdbg_dataGrid["ID_Shift", e.RowIndex].Value = lds.Tables[0].Rows[0]["ID_Shift"];
                    mdbg_dataGrid["Shift_Name", e.RowIndex].Value = lds.Tables[0].Rows[0]["Shift_Name"];
                    mdbg_dataGrid["Begin_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["End_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    mdbg_dataGrid["Time_In", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["Time_Out", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    
                }
            }
            else if (e.ColumnIndex == 2)
            {
                ls_SQL = "select PS.ID_Shift, DS.Shift_Name, DS.Begin_Hrs, DS.End_Hrs "
                        + " From dbo.HRM_PersonnelShift PS inner join dbo.HRM_DefineShift DS on PS.ID_Shift = DS.ID_Shift "
                        + " where PS.ID_Emp = '" + ls_IDEmp + "' "
                        + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) "
                        + " and Convert(varchar(8), PS.End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) ";
                lds = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelShift");
                if (lds.Tables[0].Rows.Count > 0)
                {
                    mdbg_dataGrid["ID_Shift", e.RowIndex].Value = lds.Tables[0].Rows[0]["ID_Shift"];
                    mdbg_dataGrid["Shift_Name", e.RowIndex].Value = lds.Tables[0].Rows[0]["Shift_Name"];
                    mdbg_dataGrid["Begin_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["End_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    mdbg_dataGrid["Time_In", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["Time_Out", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    
                }
            }
        }
        #endregion

    }
}
